from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from aijia_project.utils.Error_statuscode import ErrorCode
from aijia_project.qiniuyun.upload_image import upload_image2QINIU
from houses.models import HouseImage, House


# /api/v1.0/houses/[int:house_id]/images
class HouseImageView(GenericAPIView):
    """添加房源图片"""

    def post(self, request, pk):
        # house_image是InMemoryUploadedFile类的实例
        house_image = request.data['house_image']
        # house_image的_name属性是图片的名字
        image_name = house_image._name
        # image是Bytes类型的图片
        image = house_image.file.read()
        # 上传图片至七牛云并且得到图片的url
        image_url = upload_image2QINIU(image, image_name)

        # HouseImage表中存储图片
        HouseImage.objects.create(
            url=image_url,
            house_id=pk
        )

        # 如果该房源没有默认首页展示图片则将该图片作为首页展示图片
        house = House.objects.get(id=pk)
        if not house.index_image_url:
            house.index_image_url = image_url
            house.save()

        return Response({
            "data": {
                "url": image_url
            },
            "errno": ErrorCode.OK,
            "errmsg": "图片上传成功"
        })
